package qbfiles;

import java.io.File;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import misc.ImprovedByteStream;

public class QbFileHandler {
  private Map<Integer, String> fields;
  private ImprovedByteStream byteStream;
  
  public Map<Integer, String> getFields() {
    return fields;
  }

  public QbFileHandler(File file){
    byteStream = new ImprovedByteStream(file);
  }
  
  public ImprovedByteStream getByteStream(){
    return byteStream;
  }
  
  public boolean createTable(){
    fields = new HashMap<Integer, String>();
    byteStream.movePosition(-2);
    
    while(readNextField());
    byteStream.reset();
    return true;
  }
  
  private boolean readNextField(){
    if(!byteStream.movePosition(2))
      return false;
    
    byte[] ident = new byte[4];
    if(!byteStream.read(ident))
      return false;
    
    byte[] figure = {0x00};
    int stringLength = byteStream.getCountToFigure(figure);
    if(stringLength == -1)
      return false;
    
    byte[] stringBytes = new byte[stringLength];
    byteStream.read(stringBytes);
    
    fields.put(ByteBuffer.wrap(ident).getInt(), new String(stringBytes));
    
    return true;
  }
}
